package com.yiwei.ydd.fragment;

import android.Manifest;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.lljjcoder.citylist.bean.CityInfoBean;
import com.viewpagerindicator.LinePageIndicator;
import com.yiwei.ydd.R;
import com.yiwei.ydd.activity.AMapActivity;
import com.yiwei.ydd.activity.NowRechargeActivity;
import com.yiwei.ydd.activity.PacketRechargeActivity;
import com.yiwei.ydd.activity.ProvinceSelectActivity;
import com.yiwei.ydd.activity.ShareIndexActivity;
import com.yiwei.ydd.activity.WebViewActivity;
import com.yiwei.ydd.adapter.HomeServiceAdapter;
import com.yiwei.ydd.api.Api;
import com.yiwei.ydd.api.bean.TodayPriceBean;
import com.yiwei.ydd.api.model.IndexModel;
import com.yiwei.ydd.api.model.IndexUserLogModel;
import com.yiwei.ydd.api.model.ShareInfoModel;
import com.yiwei.ydd.api.model.TodayPriceModel;
import com.yiwei.ydd.base.PermissionActivity;
import com.yiwei.ydd.constant.UserInfoGlobal;
import com.yiwei.ydd.util.GlideImageLoader;
import com.yiwei.ydd.util.Network;
import com.yiwei.ydd.util.RxLifeUtil;
import com.yiwei.ydd.util.ShareUtil;
import com.yiwei.ydd.util.ToastUtil;
import com.yiwei.ydd.util.Util;
import com.yiwei.ydd.view.CustomViewPager;
import com.yiwei.ydd.view.NoticeView;
import com.yiwei.ydd.view.ObservableScrollView;
import com.yiwei.ydd.view.RightIconText;
import com.yiwei.ydd.view.V19RelativeLayout;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by xsooy-pc on 17-12-4.
 */

public class MainHomeFragment extends BaseFragment implements AMapLocationListener, ObservableScrollView.ScrollViewListener {

    @BindView(R.id.index_banner)
    Banner indexBanner;
    @BindView(R.id.txt_location)
    TextView txtLocation;
    @BindView(R.id.img_msg_tips)
    ImageView imgMsgTips;
    @BindView(R.id.txt_notice)
    NoticeView txtNotice;
    @BindView(R.id.txt_address_title)
    TextView txtAddressTitle;
    @BindView(R.id.txt_price_92)
    RightIconText txtPrice92;
    @BindView(R.id.txt_price_95)
    RightIconText txtPrice95;
    @BindView(R.id.txt_price_0)
    RightIconText txtPrice0;
    @BindView(R.id.txt_packet_title)
    TextView txtPacketTitle;
    @BindView(R.id.txt_packet_desc)
    TextView txtPacketDesc;
    @BindView(R.id.btn_packet_recharge)
    LinearLayout btnPacketRecharge;
    @BindView(R.id.txt_now_title)
    TextView txtNowTitle;
    @BindView(R.id.txt_now_desc)
    TextView txtNowDesc;
    @BindView(R.id.btn_now_recharge)
    LinearLayout btnNowRecharge;
    @BindView(R.id.btn_invite)
    LinearLayout btnInvite;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.indicator)
    LinePageIndicator indicator;
    @BindView(R.id.pager)
    CustomViewPager pager;
    @BindView(R.id.list)
    RecyclerView list;
    @BindView(R.id.scrollView)
    ObservableScrollView scrollView;
    @BindView(R.id.txt_location_sec)
    TextView txtLocationSec;
    @BindView(R.id.img_msg_tips_sec)
    ImageView imgMsgTipsSec;
    @BindView(R.id.toolbar)
    V19RelativeLayout toolbar;
    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.img_notice_icon)
    CircleImageView imgNoticeIcon;
    @BindView(R.id.txt_notice_info)
    TextView txtNoticeInfo;
    @BindView(R.id.layout_notice)
    LinearLayout layoutNotice;
    private Unbinder unbinder;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private HomeServiceAdapter adapter;
    private float headerHeight;
    private float minHeaderHeight;
    private String nowCity;
    private String nowProvince;
    private ObjectAnimator animation;
    private int num;
    private List<IndexUserLogModel.DatasBean> invite_list;

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_main_home;
    }

    @Override
    protected void initView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            headerHeight = getResources().getDimensionPixelSize(R.dimen.y208);
        } else {
            headerHeight = getResources().getDimensionPixelSize(R.dimen.y168);
        }
        minHeaderHeight = getResources().getDimension(R.dimen.y98);
//        dialog = new LoginDialog(getContext());
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initLocation();
                getIndex();
            }
        });
        scrollView.setScrollViewListener(this);
        initLocation();
//        List<String> stringList = new ArrayList<>();
//        stringList.add("我是测试一号");
//        stringList.add("我是测试二号");
//        stringList.add("我是测试三号");
//        txtNotice.setList(stringList);
        adapter = new HomeServiceAdapter(getContext());
        list.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        list.setNestedScrollingEnabled(false);
        list.setAdapter(adapter);
        indexBanner.setImageLoader(new GlideImageLoader());
        indexBanner.setIndicatorGravity(BannerConfig.RIGHT);
        initAnimation();
        getIndex();
    }


    private void initLocation() {

//        if (mlocationClient == null) {
        //初始化定位
        mlocationClient = new AMapLocationClient(getContext());
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位回调监听
        mlocationClient.setLocationListener(this);
        //设置为高精度定位模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setOnceLocation(true);
        //设置定位参数
        mlocationClient.setLocationOption(mLocationOption);
        // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
        // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
        // 在定位结束后，在合适的生命周期调用onDestroy()方法
        // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
//        }
        checkPermission(new PermissionActivity.CheckPermListener() {
            @Override
            public void superPermission() {
                mlocationClient.startLocation();
            }
        }, R.string.location_permission, R.string.get_location, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
        unbinder.unbind();
    }

    private void initAnimation() {
        animation = ObjectAnimator.ofFloat(layoutNotice, "alpha", 0f, 1f, 1f, 1f, 0f, 0f, 0f, 0f, 0f);
        animation.setRepeatCount(-1);
        animation.setDuration(8000);
        animation.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                Glide.with(getContext()).load(invite_list.get(0).icon).error(R.mipmap.img_home_default_icon).into(imgNoticeIcon);
                txtNoticeInfo.setText(invite_list.get(0).desc);
            }

            @Override
            public void onAnimationEnd(Animator animation) {

            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {
                int poi = num++ % invite_list.size();
                txtNoticeInfo.setText(invite_list.get(poi).desc);
                Glide.with(getContext()).load(invite_list.get(poi).icon).error(R.mipmap.img_home_default_icon).into(imgNoticeIcon);
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (invite_list != null && invite_list.size() != 0) {
            if (animation == null) {
                initAnimation();
            }
            animation.start();
        } else {
            getUserLog();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (animation != null) {
            animation.cancel();
        }
    }

    public void setLocation(String city, String province) {
        if (city.equals(nowCity)) {
            province = nowProvince;
        }
        txtLocation.setText(city);
        txtLocationSec.setText(city);
        getTodayPrice(province.replace("省", "").replace("市", ""), city);
    }

    public void getUserLog() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }

        Api.api_service.getIndexUserLog().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    invite_list = result.datas;
                    if (animation == null) {
                        initAnimation();
                    }
                    animation.start();
                });
    }

    public void getIndex() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }

        if (refresh != null) {
            refresh.setRefreshing(true);
        }
        Api.api_service.getIndex().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setData(result.datas);
                });
    }

    public void getTodayPrice(String location, String city) {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }

        if (refresh != null) {
            refresh.setRefreshing(true);
        }
        TodayPriceBean bean = new TodayPriceBean();
        bean.location = location;
        Api.api_service.getTodayPrice(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    txtAddressTitle.setText(city + "今日油价");
                    setTodayPrice(result.datas);
                });
    }

    private void setTodayPrice(TodayPriceModel.DatasBean datas) {
        if (datas.items != null && datas.items.size() != 0) {
            for (int i = 0; i < datas.items.size(); i++) {
                TodayPriceModel.DatasBean.ItemsBean item = datas.items.get(i);
                switch (datas.items.get(i).item) {
                    case "0":
                        txtPrice0.setTextString(item.price);
//                        （-1：降价，0：没有变化，1：升价）
                        if (item.change.equals("-1")) {
                            txtPrice0.setDrawable(R.mipmap.img_home_oil_down);
                        } else if (item.change.equals("0")) {
                            txtPrice0.setDrawable(R.mipmap.img_home_oil_equal);
                        } else if (item.change.equals("1")) {
                            txtPrice0.setDrawable(R.mipmap.img_home_oil_up);
                        }
                        break;
                    case "92":
                        txtPrice92.setTextString(item.price);
                        if (item.change.equals("-1")) {
                            txtPrice92.setDrawable(R.mipmap.img_home_oil_down);
                        } else if (item.change.equals("0")) {
                            txtPrice92.setDrawable(R.mipmap.img_home_oil_equal);
                        } else if (item.change.equals("1")) {
                            txtPrice92.setDrawable(R.mipmap.img_home_oil_up);
                        }
                        break;
                    case "95":
                        txtPrice95.setTextString(item.price);
                        if (item.change.equals("-1")) {
                            txtPrice95.setDrawable(R.mipmap.img_home_oil_down);
                        } else if (item.change.equals("0")) {
                            txtPrice95.setDrawable(R.mipmap.img_home_oil_equal);
                        } else if (item.change.equals("1")) {
                            txtPrice95.setDrawable(R.mipmap.img_home_oil_up);
                        }
                        break;
                }
            }
        }
    }

    private void setData(IndexModel.DatasBean item) {

        txtPacketTitle.setText(item.term.title);
        txtPacketDesc.setText(item.term.desc);

        txtNowTitle.setText(item.instant.title);
        txtNowDesc.setText(item.instant.desc);
//        Spanned tips_one = Spans.with(getContext()).font(item.instant.title + "\n", getResources().getDimensionPixelSize(R.dimen.x40), 0xffffffff).style(Typeface.BOLD).
//                font(item.instant.desc, getResources().getDimensionPixelSize(R.dimen.x22), 0xffffffff).
//                build();
//        txtInstantTips.setText(tips_one);
//
//
//        txtInstantTipsTwo.setText(item.instant.note);
//        btnOilRecharge.setText(item.instant.btn);
//
//        Spanned tips_two = Spans.with(getContext()).font(item.term.title + "\n", getResources().getDimensionPixelSize(R.dimen.x40), 0xffffffff).style(Typeface.BOLD).
//                font(item.term.desc, getResources().getDimensionPixelSize(R.dimen.x22), 0xffffffff).
//                build();
//        txtTermTips.setText(tips_two);
//        txtTermTipsTwo.setText(item.term.note);
//        btnPacketOil.setText(item.term.btn);

        adapter.update(item.services);


        if (item.index_banner == null) {
            return;
        }
        List<String> bannerdata = new ArrayList<>();
        for (int i = 0; i < item.index_banner.size(); i++) {
            bannerdata.add(item.index_banner.get(i).icon);
        }
        indexBanner.setImages(bannerdata).setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
//                if (TextUtils.isEmpty(item.index_banner.get(position).url)) {
//                    return;
//                }
//                Intent intent = new Intent(getContext(), WebViewActivity.class);
//                intent.putExtra("url", item.index_banner.get(position).url);
//                startActivity(intent);
//                getActivity().overridePendingTransition(R.anim.right_enter, R.anim.left_out);
            }
        }).start();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100) {
            if (data != null) {
                Bundle bundle = data.getExtras();
                CityInfoBean cityInfoBean = bundle.getParcelable("cityinfo");
                txtLocation.setText(cityInfoBean.getName());
                txtLocationSec.setText(cityInfoBean.getName());
            }
        }
    }

    public void getShareInfo() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }

        if (refresh != null) {
            refresh.setRefreshing(true);
        }
        Api.api_service.getShareInfo().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        refresh.setRefreshing(false);
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ShareInfoModel.DatasBean item = result.datas;
                    ShareUtil.share(getContext(), item.desc, item.image, item.title, item.url);
                });
    }

    @OnClick({R.id.btn_invite, R.id.img_msg_tips_sec, R.id.txt_location_sec, R.id.txt_location, R.id.img_msg_tips, R.id.btn_now_recharge, R.id.btn_packet_recharge})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_location:
            case R.id.txt_location_sec:
                Util.startActivity(getActivity(), ProvinceSelectActivity.class);
                break;
            case R.id.img_msg_tips:
            case R.id.img_msg_tips_sec:
                Util.startActivity(getActivity(), AMapActivity.class);
                break;
            case R.id.btn_invite:
//                if (Util.getIsLogin(getContext())) {
//                    MobclickAgent.onEvent(getContext(), "Home_Recharge_Share");
//                    getShareInfo();
//                }
                if (Util.getIsLogin(getContext()))
                    Util.startActivity(getActivity(), ShareIndexActivity.class);
                break;
            case R.id.btn_now_recharge:
                if (Util.getIsLogin(getContext()))
                    Util.startActivity(getActivity(), NowRechargeActivity.class);
                break;
            case R.id.btn_packet_recharge:
                if (Util.getIsLogin(getContext()))
                    Util.startActivity(getActivity(), PacketRechargeActivity.class);
                break;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        indexBanner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        indexBanner.stopAutoPlay();
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (refresh != null) {
            refresh.setRefreshing(false);
        }
        if (amapLocation.getErrorCode() == 0) {
            txtLocation.setText(amapLocation.getCity());
            txtLocationSec.setText(amapLocation.getCity());
            nowProvince = amapLocation.getProvince().replace("省", "").replace("市", "");
            nowCity = amapLocation.getCity();
            UserInfoGlobal.setNowCity(nowCity);
            getTodayPrice(nowProvince, nowCity);
        } else {
//            String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
            UserInfoGlobal.setNowCity("");
            ToastUtil.makeText(getContext(), "定位失败，请开启定位权限");
            getTodayPrice("", "");
        }
    }


    @Override
    public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx, int oldy) {
        //Y轴偏移量
        float scrollY = scrollView.getScrollY();
//        e3483d
        //变化率
        float headerBarOffsetY = headerHeight - minHeaderHeight;//Toolbar与header高度的差值
        float offset = 1 - Math.max((headerBarOffsetY - scrollY) / headerBarOffsetY, 0f);

        //Toolbar背景色透明度


        if (scrollY >= headerHeight) {
            toolbar.setVisibility(View.VISIBLE);
            toolbar.setAlpha(1);
//            txtCenterTitle.setText("油多多");
//            toolbar.setBackgroundColor(Color.argb(255, 81, 119, 254));
//            if (toolbar.getVisibility() == View.GONE) {
//                return;
//            }
        } else {
//            txtCenterTitle.setText("");
//            if (layoutToolbar.getVisibility() == View.VISIBLE) {
//                layoutToolbar.setBackgroundColor(Color.argb((int) (offset * 255), 81, 119, 254));
//                return;
//            }
            if (scrollY == 0) {
                toolbar.setVisibility(View.GONE);
            } else {
                toolbar.setVisibility(View.VISIBLE);
                toolbar.setAlpha(offset);
//                toolbar.setBackgroundColor(Color.argb((int) (offset * 255), 81, 119, 254));
            }
        }
    }
}
